package com.millstein.config;

import com.millstein.properties.RabbitMQProperties;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-21 16:06
 */
@Configuration
@EnableConfigurationProperties(RabbitMQProperties.class)
public class RabbitMQConfig {

    @Autowired
    private RabbitMQProperties rabbitMQProperties;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Exchange exchange() {
        return ExchangeBuilder
                .topicExchange(rabbitMQProperties.getProductEventExchange())
                .durable(true)
                .build();
    }

    @Bean
    public Queue delayQueue() {
        return QueueBuilder
                .durable(rabbitMQProperties.getProductReleaseDelayQueue())
                .deadLetterExchange(rabbitMQProperties.getProductEventExchange())
                .deadLetterRoutingKey(rabbitMQProperties.getProductReleaseRoutingKey())
                .ttl(Integer.parseInt(rabbitMQProperties.getTtl()))
                .build();
    }

    @Bean
    public Binding bindingDelayQueue() {
        return BindingBuilder
                .bind(delayQueue())
                .to(exchange())
                .with(rabbitMQProperties.getProductReleaseDelayRoutingKey())
                .noargs();
    }

    @Bean
    public Queue normalQueue() {
        return QueueBuilder
                .durable(rabbitMQProperties.getProductReleaseQueue())
                .build();
    }

    @Bean
    public Binding bindingNormalQueue() {
        return BindingBuilder
                .bind(normalQueue())
                .to(exchange())
                .with(rabbitMQProperties.getProductReleaseRoutingKey())
                .noargs();
    }
}
